/*
 * Copyright 2011 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy.anim.timer
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	import sweezy.anim.core.ITimer;

	public class FrameTimer extends TimerBase implements ITimer
	{

		private var _binData:Array = [
			0x4657530a, 0x1a000000, 0x09800000,
			0x02004411, 0x08000000, 0x40004000,
			0x00000000];

		private var _mc:MovieClip;

		public function FrameTimer()
		{
		}

		override protected function onDestroy():void
		{
			_mc.stop();
			_mc = null;
		}

		override protected function onInitialize():void
		{
			var bytes:ByteArray = new ByteArray();
			for (var i:int = 0, len:uint = _binData.length; i < len; i++)
			{
				bytes.writeInt(_binData[i]);
			}

			var loader:Loader = new Loader();
			var info:LoaderInfo = loader.contentLoaderInfo;
			info.addEventListener(Event.COMPLETE, completeHandler);
			loader.loadBytes(bytes);
		}

		private function completeHandler(e:Event):void
		{
			var info:LoaderInfo = e.currentTarget as LoaderInfo;
			info.removeEventListener(Event.COMPLETE, completeHandler);

			var loader:Loader = info.loader;
			_mc = loader.content as MovieClip;

			_mc.addFrameScript(0, handler);
			_mc.addFrameScript(1, handler);
			
			handler();
		}

		private function handler():void
		{
			_client.tick(_time = getTimer());
		}
	}
}
